package com.ruoyi.project.system.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.utils.SecurityUtils;
// import com.ruoyi.framework.aspectj.lang.annotation.Anonymous; // 如果不需要匿名访问，请注释或删除此行
import com.ruoyi.project.system.domain.SysDoctor;
import com.ruoyi.project.system.domain.RecoverSuggest;
import com.ruoyi.project.system.service.ISysDoctorService;
import com.ruoyi.project.system.service.RecoverSuggestService;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/rehab")
public class RehabController {

    // 修正：变量命名遵循驼峰命名法
    @Autowired
    private ISysDoctorService sysDoctorService;

    @Autowired
    private RecoverSuggestService recoverSuggestService;

    /**
     * 获取康复建议
     * @return 分类后的康复建议
     */
    // 修正：如果不需要匿名访问，请移除 @Anonymous 注解
    @GetMapping("/advice")
    public ResponseEntity<?> getRehabAdvice() {
        // 1. 获取当前用户ID
        Long userId = SecurityUtils.getUserId(); 
        if (userId == null) {
            return ResponseEntity.badRequest().body("无法获取当前用户信息");
        }
        
        // 2. 根据用户ID查询医生信息
        // 修正：使用修改后的变量名调用方法
        SysDoctor sysDoctor = sysDoctorService.getDoctorInfoByUserId(userId);
        if (sysDoctor == null) {
            return ResponseEntity.badRequest().body("未找到该用户对应的医生信息");
        }

        Integer departmentId = sysDoctor.getDepartmentId();
        if (departmentId == null) {
            return ResponseEntity.badRequest().body("医生信息中未配置科室ID");
        }

        // 3. 根据科室ID查询所有康复建议
        List<RecoverSuggest> suggestions = recoverSuggestService.getSuggestionsByDeptId(departmentId);

        // 4. 按 topic 分类建议
        Map<String, List<String>> categorizedAdvice = suggestions.stream()
                .collect(Collectors.groupingBy(
                    RecoverSuggest::getTopic,
                    Collectors.mapping(RecoverSuggest::getSuggest, Collectors.toList())
                ));

        // 5. 确保所有分类都存在，即使为空
        categorizedAdvice.computeIfAbsent("sports", k -> Collections.emptyList());
        categorizedAdvice.computeIfAbsent("sleep", k -> Collections.emptyList());
        categorizedAdvice.computeIfAbsent("diet", k -> Collections.emptyList());

        // 6. 返回结果
        return ResponseEntity.ok(categorizedAdvice);
    }
}